const express = require('express'),
    multiparty = require('multiparty'),
    util = require('util'),
    fs = require('fs'),
    path = require('path'),
    mongoose = require('mongoose'),
    app = express(),
    Person = require('./Models/Person');

app.use('/public', express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
    res.end(fs.readFileSync(path.join(__dirname, 'index.html')))
});
app.post('/fileUploader', (req, res) => {
    res.header({
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Methods': '*',
        'Access-Control-Allow-Origin': '*'
    });
    var form = new multiparty.Form({
        uploadDir: path.join(__dirname, 'files')
    });
    form.parse(req, (err, fields, files) => {
        var fileTmp = JSON.stringify(files, null, 2);
        if (err) console.error(err);
        else {

        }
        res.writeHead(200, {
            'content-type': 'text/plain;charset=utf-8;'
        });
        res.end(util.inspect({
            fields,
            files: fileTmp
        }));
    });
});

var persons = [{
        name: 'Smith',
        age: 13,
        sex: '女'
    },
    {
        name: 'Jane',
        age: 20,
        sex: '女'
    },
    {
        name: 'Jack',
        age: 22,
        sex: '男'
    },
    {
        name: 'Michael',
        age: 15,
        sex: '男'
    }
];
app.get('/person/:name', (req, res) => {
    res.header('access-control-allow-origin', '*');
    var name = req.params.name;
    Person.findOne({
        name
    }).then(person => {
        if (person != null) {
            res.json(person)
        } else {
            res.json({
                msg: '查无此人！'
            })
        }
    })
    // var result = persons.find(item => name == item.name);
    // res.json(result);
});
mongoose.connect('mongodb://duanjinqiu.cn:27017/nodejs', err => {
    if (err) console.error('数据库连接失败!');
    else {
        var server = app.listen(8081, () => console.info(`listening on port in ${server.address().port}`));
    }
});